package com.woniuxy.shop.servelet.front;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.woniuxy.shop.entity.PreOrder;
import com.woniuxy.shop.entity.ResponseEntity;
import com.woniuxy.shop.entity.User;
import com.woniuxy.shop.exception.ServiceException;
import com.woniuxy.shop.service.ServiceProxyFactory;
import com.woniuxy.shop.service.UserService;
import com.woniuxy.shop.utils.ShopUtils;

/**
 * Servlet implementation class CateGoryServelet
 */
@WebServlet("/user")
@MultipartConfig
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserService us = ServiceProxyFactory.getProxy(UserService.class);

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opr = request.getParameter("opr");
		if ("register".equals(opr)) {
			doRegister(request, response);
		} else if ("login".equals(opr)) {
			doLogin(request, response);
		} else if ("logout".equals(opr)) {
			doLogout(request, response);
		} else if ("active".equals(opr)) {
			doActive(request, response);
		} else if ("sendMail".equals(opr)) {
			doSendMail(request, response);
		} else if ("check".equals(opr)) {
			doCheck(request, response);
		} else if ("checkPwd".equals(opr)) {
			doCheckPwd(request, response);
		} else if ("updatePwd".equals(opr)) {
			doUpdatePwd(request, response);
		} else if ("upload".equals(opr)) {
			doUpload(request, response);
		}

	}

	private void doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		ResponseEntity<String> rese = new ResponseEntity<>();
		try {
			Part part = request.getPart("file");
			String path = getServletContext().getRealPath("/images/avatar");
			// 产生一个唯一的文件名
			String fileName = UUID.randomUUID().toString().replaceAll("-", "");
			part.write(path + "/" + fileName);
			String image = "images/avatar/" + fileName;
			User u = (User)request.getSession().getAttribute("user");
			u.setAvatar(image);
			us.uploadAvatar(u.getId(),image);
			request.getSession().invalidate();
			request.getSession().setAttribute("user", u);
			rese.setCode(200);
			rese.setMsg("ok");
			rese.setData(image);
			ShopUtils.write(response, rese);
		} catch (Exception e) {
			rese.setData("");
			rese.setCode(101);
			rese.setMsg("error");
			ShopUtils.write(response, rese);
		}
		
	}

	private void doUpdatePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ResponseEntity<Void> rese = new ResponseEntity<Void>();
		String oldpwd = request.getParameter("oldpwd");
		String newpwd = request.getParameter("newpwd");
		String repwd = request.getParameter("repwd");
		User u = (User) request.getSession().getAttribute("user"); 
		if (u == null) {
			response.sendRedirect("../usernotlogin.jsp");
			return;
		}
		// 密码格式校验
		if(!u.getPassword().equals(oldpwd)) {
			rese.setCode(101);
			rese.setMsg("密码错误");
			ShopUtils.write(response, rese);
			return;
		}
		if (newpwd == null || newpwd.trim().equals("")) {
			rese.setMsg("新密码为空");
			rese.setCode(101);
			ShopUtils.write(response, rese);
			return;
		} else {
			newpwd = newpwd.trim();
		}
		if (newpwd.length() < 6 || newpwd.length() > 32) {
			rese.setMsg("新密码长度错误");
			rese.setCode(101);
			ShopUtils.write(response, rese);			
			return;
		}
		// 确认密码校验
		if (repwd == null) {
			rese.setMsg("确认密码为空");
			rese.setCode(101);
			ShopUtils.write(response, rese);			
			return;
		} else {
			repwd = repwd.trim();
		}
		if (!newpwd.equals(repwd)) {
			rese.setMsg("更改密码不一致");
			rese.setCode(101);
			ShopUtils.write(response, rese);			
			return;
		}
		
		try {
			us.updatePwd(u.getId(),newpwd);
			rese.setCode(200);
			ShopUtils.write(response, rese);			
		} catch (ServiceException e) {
			rese.setMsg("服务器异常");
			rese.setCode(101);
			ShopUtils.write(response, rese);			
		}

	}

	private void doCheckPwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String pwd = request.getParameter("pwd");
		User u = (User) request.getSession().getAttribute("user");
		if (u == null) {
			response.sendRedirect("../usernotlogin.jsp");
			return;
		}
		if (u.getPassword().equals(pwd)) {
			response.getWriter().write("true");
		} else {
			response.getWriter().write("false");
		}

	}

	/**
	 * 校验邮箱及账号是否有重复
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String act = request.getParameter("checkAccount");
		String email = request.getParameter("checkEmail");
		// 如果账号不为空则要验证账号的唯一性
		if (act != null) {
			response.getWriter().write(String.valueOf(ShopUtils.checkActOrEmail(1, act)));
		}
		// 如果邮箱不为空则要验证账号的唯一性
		if (email != null) {
			response.getWriter().write(String.valueOf(ShopUtils.checkActOrEmail(0, email)));
		}
	}

	private void doSendMail(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ResponseEntity<Void> rese = new ResponseEntity<Void>();
		try {
			String email = request.getParameter("email");
			ShopUtils.sendMail(email);
		} catch (Exception e) {
			rese.setCode(101);
		}
		rese.setCode(200);
		ShopUtils.write(response, rese);

	}

	/**
	 * 激活邮箱
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void doActive(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		User uSession = (User) request.getSession().getAttribute("user");

		try {
			String email = request.getParameter("email");
			us.active(email);
			// 如果session中user为空，则自动登录
			User u = us.getUserByEmail(email);
			if (uSession == null) {
				request.getSession().setAttribute("user", u);
				uSession = u;
			}
		} catch (Exception e) {
			System.out.println(e);
		}

		request.setAttribute("activeok", uSession.getAccount() + "恭喜您，激活邮箱成功！");
		request.getRequestDispatcher("index").forward(request, response);
	}

	private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.getSession().invalidate();
		response.sendRedirect("login.jsp");

	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String account = request.getParameter("account");
		String pwd = request.getParameter("password");
		User u = null;
		try {
			u = us.getUserByAct(account);
			// 校验账户是否存在
			if (u == null) {
				ShopUtils.responseTo("failmsg", "该账户不存在", "login.jsp", request, response);
				return;
			}
			// 密码校验
			if (!u.getPassword().equals(pwd)) {
				ShopUtils.responseTo("failmsg", "密码错误", "login.jsp", request, response);
				return;
			}
		} catch (ServiceException e) {
			ShopUtils.responseTo("failmsg", "系统维护中，请稍后再试", "login.jsp", request, response);
		}
		request.getSession().setAttribute("user", u);
		List<PreOrder> pos = (List<PreOrder>) request.getAttribute("List<PreOrder>");
		if (u.getStatus().equals("1")) {
			request.setAttribute("notActiveEmail", u.getEmail());
			request.getRequestDispatcher("login.jsp").forward(request, response);
		} else if (pos != null) {
			// 若预订单的信息系不为空，则转到订单添加界面
			request.getRequestDispatcher("order?opr=initialAdd").forward(request, response);
		} else {
			response.sendRedirect("index");
		}
	}

	/*
	 * 处理用户注册相关逻辑
	 */
	private void doRegister(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取数据
		String uact = request.getParameter("account");
		String upwd = request.getParameter("password");
		String repwd = request.getParameter("repassword");
		String utel = request.getParameter("phoneNum");
		String uemail = request.getParameter("email");
		String captcha = request.getParameter("captcha");
		// 进行数据有效性校验并针对问题数据给出相应处理
		// 账号格式校验
		if (uact == null || uact.trim().equals("")) {
			ShopUtils.responseTo("actmsg", "账号不能为空", "register.jsp", request, response);
			return;
		} else {
			// 若账号不为null则去掉首尾空格
			uact = uact.trim();
		}
		if (uact.length() < 2 || uact.length() > 20) {
			ShopUtils.responseTo("actmsg", "账号长度有误", "register.jsp", request, response);
			return;
		}
		// 针对账号是否是规定字符进行校验
		if (!ShopUtils.checkAct(uact)) {
			ShopUtils.responseTo("actmsg", "账号格式错误", "register.jsp", request, response);
			return;
		}
		// 针对账号唯一性校验
		if (!ShopUtils.checkActOrEmail(1, uact)) {
			ShopUtils.responseTo("actmsg", "该账号已被注册", "register.jsp", request, response);
			return;
		}

		// 密码格式校验
		if (upwd == null || upwd.trim().equals("")) {
			ShopUtils.responseTo("pwdmsg", "密码不能为空", "register.jsp", request, response);
			return;
		} else {
			upwd = upwd.trim();
		}
		if (upwd.length() < 6 || upwd.length() > 32) {
			ShopUtils.responseTo("pwdmsg", "密码长度有误", "register.jsp", request, response);
			return;
		}
		// 确认密码校验
		if (repwd == null) {
			ShopUtils.responseTo("repwdmsg", "确认密码不能为空", "register.jsp", request, response);
			return;
		} else {
			repwd = repwd.trim();
		}
		if (!upwd.equals(repwd)) {
			ShopUtils.responseTo("repwdmsg", "密码不一致", "register.jsp", request, response);
			return;
		}

		// 确认手机号码
		if (utel == null) {
			ShopUtils.responseTo("phonemsg", "确认密码不能为空", "register.jsp", request, response);
			return;
		} else {
			utel = utel.trim();
		}
		if (!ShopUtils.checkPhone(utel)) {
			ShopUtils.responseTo("phonemsg", "手机号码格式错误", "register.jsp", request, response);
			return;
		}

		// 校验邮箱
		if (uemail == null) {
			ShopUtils.responseTo("emailmsg", "邮箱不能为空", "register.jsp", request, response);
			return;
		} else {
			uemail = uemail.trim();
		}
		if (!ShopUtils.checkMail(uemail)) {
			ShopUtils.responseTo("emailmsg", "邮箱地址不合法", "register.jsp", request, response);
			return;
		}
		if (!ShopUtils.checkActOrEmail(0, uemail)) {
			ShopUtils.responseTo("emailmsg", "该邮箱已被注册", "register.jsp", request, response);
			return;
		}
		String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
		if (!captcha.equals(sessionCaptcha)) {
			ShopUtils.responseTo("capmsg", "验证码错误", "register.jsp", request, response);
			return;
		}
		// 访问数据库处理注册业务逻辑
		// 创建user对象
		User u = new User();
		u.setAccount(uact);
		u.setEmail(uemail);
		u.setPassword(upwd);
		u.setPhonenum(utel);
		// 设置默认属性
		u.setAvatar("images/front/user_ico.gif");
		u.setStatus("1");// 1表示未激活

		try {
			us.register(u);
			// 往注册的邮箱中发送激活码进行激活
			ShopUtils.sendMail(uemail);
		} catch (ServiceException e) {
//			request.setAttribute("fail", "系统维护中，请稍后再试！");
//			request.getRequestDispatcher("register.jsp").forward(request, response);
			ShopUtils.responseTo("fail", "系统维护中，请稍后再试！", "register.jsp", request, response);
		}
		String sucmsg = "您的账号：" + uact + "已注册成功";
		ShopUtils.responseTo("regSuccess", sucmsg, "register.jsp", request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
